package com.jz.community.moduleshoppingguide.neighbor.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jz.community.basecomm.base.BaseMvpLoadFragment;
import com.jz.community.basecomm.bean.BaseCommLocateInfo;
import com.jz.community.basecomm.glideConfig.GlideApp;
import com.jz.community.basecomm.loaction.LocationActivity;
import com.jz.community.basecomm.loaction.LocationManager;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.RxDataTool;
import com.jz.community.basecomm.utils.eventbus.AppEvent;
import com.jz.community.basecomm.utils.eventbus.EventConfig;
import com.jz.community.commview.callback.ErrorCallback;
import com.jz.community.commview.callback.LoadingCallback;
import com.jz.community.commview.callback.LocationCallback;
import com.jz.community.moduleshoppingguide.R;
import com.jz.community.moduleshoppingguide.R2;
import com.jz.community.moduleshoppingguide.neighbor.bean.CircleMessageBean;
import com.jz.community.moduleshoppingguide.neighbor.bean.NearCircleListBean;
import com.jz.community.moduleshoppingguide.neighbor.presenter.NeighborNearPresenter;
import com.jz.community.moduleshoppingguide.neighbor.ui.NeighborNearView;
import com.jz.community.moduleshoppingguide.neighbor.ui.activity.NeighborMessageActivity;
import com.jz.community.moduleshoppingguide.neighbor.ui.adapter.NearCircleAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

public class NeighborNearFragment extends BaseMvpLoadFragment<NeighborNearView.View, NeighborNearPresenter> implements NeighborNearView.View, OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {
    @BindView(R2.id.neighbor_near_address_tv)
    TextView neighborNearAddressTv;
    @BindView(R2.id.neighbor_near_address_ll)
    LinearLayout neighborNearAddressLl;
    @BindView(R2.id.neighbor_near_address_line)
    ImageView neighborNearAddressLine;
    @BindView(R2.id.neighbor_near_message_iv)
    ImageView neighborNearMessageIv;
    @BindView(R2.id.neighbor_near_message_name)
    TextView neighborNearMessageName;
    @BindView(R2.id.neighbor_near_message_num)
    TextView neighborNearMessageNum;
    @BindView(R2.id.neighbor_near_message_rl)
    RelativeLayout neighborNearMessageRl;
    @BindView(R2.id.neighbor_near_head_iv1)
    CircleImageView neighborNearHeadIv1;
    @BindView(R2.id.neighbor_near_head_iv2)
    CircleImageView neighborNearHeadIv2;
    @BindView(R2.id.neighbor_near_head_iv3)
    CircleImageView neighborNearHeadIv3;
    @BindView(R2.id.neighbor_near_arrow)
    ImageView neighborNearArrow;
    @BindView(R2.id.neighbor_near_info_ll)
    LinearLayout neighborNearInfoLl;
    @BindView(R2.id.neighbor_near_rv)
    RecyclerView neighborNearRv;
    @BindView(R2.id.neighbor_near_refresh)
    SmartRefreshLayout neighborNearRefresh;
    Unbinder unbinder;

    String limitDistance = "";
    private static final int CODE_COMMUNITY = 0X00001;
    private static final int CODE_LOC_SELECT = 708;

    private LocationManager lm;
    private PoiSearch poiSearch;
    private static final String SEARCH_CONTENT = "汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|" +
            "医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科" +
            "教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";

    private View noDataView;//无数据显示
    private View loadingView;//加载显示

    private int hasCircle = 0;//是否已加入圈子
    private String circle_id = "";//圈子ID

    private int page = 0;
    private int size = 10;
    private int totalPage = 0;

    private CircleMessageBean entity_message;

    private List<NearCircleListBean.EmbeddedBean.ContentBean> circle_list = new ArrayList<>();
    private NearCircleAdapter adapter_circle;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.module_shoppingguide_fragment_neighbor_near;
    }

    @Override
    protected NeighborNearPresenter createPresenter() {
        return new NeighborNearPresenter(this);
    }

    @Override
    protected void initDatas() {
        super.initDatas();
        initStatus();
        initRecyclerView();
    }

    @Override
    protected void initLazy(@Nullable Bundle savedInstanceState) {
        super.initLazy(savedInstanceState);
        beginLocation();

    }

    /**
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void EventBus(AppEvent message) {
        if (message.tag == EventConfig.REFRESH_NEAR_CIRCLE) {
            hasCircle = BaseSpUtils.getInstance().getCircleStatus(getActivity());
            page = 0;
            if (null != adapter_circle) {
                adapter_circle.replaceData(new ArrayList<>());
            }
            //需要先将所有图片隐藏，在走接口，防止图片数量错乱
            inVisibleImgs();
            if (hasCircle == 1) {
                mPresenter.initUserNeighbor();
            } else {
                String com_lat = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lat;
                String com_lon = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lon;
                mPresenter.initNearNeighbor(com_lat, com_lon, page, size);
            }
        }

    }

    private void initStatus() {
        mBaseLoadService.setCallBack(LocationCallback.class, (context, view) -> {
            TextView loc_btn1 = (TextView) view.findViewById(R.id.empty_loc_btn1);
            TextView loc_btn2 = (TextView) view.findViewById(R.id.empty_loc_btn2);

            loc_btn1.setOnClickListener(v -> {
                //手动定位
                Intent toCommunity = new Intent(getActivity(), LocationActivity.class);
                startActivityForResult(toCommunity, CODE_COMMUNITY);

            });

            loc_btn2.setOnClickListener(v -> {
                //重新定位
                beginLocation();

            });

        });

        mBaseLoadService.setCallBack(LoadingCallback.class, (context, view) -> {
            ImageView mIvLoading = (ImageView) view.findViewById(R.id.loading_img);
            GlideApp.with(getActivity())
                    .asGif()
                    .load(R.drawable.loading_default)
                    .into(mIvLoading);

        });

        mBaseLoadService.setCallBack(ErrorCallback.class, (context, view) -> {
            ImageView mIvError = (ImageView) view.findViewById(R.id.error_img);
            mIvError.setImageResource(R.mipmap.error_default);

        });

        noDataView = getLayoutInflater().inflate(R.layout.view_empty, (ViewGroup) neighborNearRv.getParent(), false);

        ImageView empty_iv = (ImageView) noDataView.findViewById(R.id.empty_img);
        TextView empty_tv = (TextView) noDataView.findViewById(R.id.empty_tv);

        empty_iv.setImageResource(R.mipmap.empty_default);
        empty_tv.setText("附近暂无圈子！");

        loadingView = getLayoutInflater().inflate(R.layout.view_loading, (ViewGroup) neighborNearRv.getParent(), false);

        ImageView loading_iv = (ImageView) loadingView.findViewById(R.id.loading_img);

        GlideApp.with(getActivity())
                .asGif()
                .load(R.drawable.loading_default)
                .into(loading_iv);
    }


    private void beginLocation() {
        lm = new LocationManager();
        lm.getLocation(result -> {
            if (result.mResultId == 0) {
                //放在定位之后
                lnToCommunity(result.mLocation.mLatitude, result.mLocation.mLongitude);
            } else {
                mBaseLoadService.showCallback(LocationCallback.class);
            }
        }, getActivity());
    }


    private void lnToCommunity(final double lat, final double lon) {
        PoiSearch.Query query = new PoiSearch.Query("", SEARCH_CONTENT, "");
        // 设置每页最多返回多少条poiItem
        query.setPageSize(10);
        //设置查询页码
        query.setPageNum(0);

        poiSearch = new PoiSearch(getActivity(), query);
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int i) {
                if (i == 1000) {
                    //成功
                    if (null != poiResult && null != poiResult.getPois() && poiResult.getPois().size() > 0) {
                        List<PoiItem> list = poiResult.getPois();

                        limitDistance = "3000";
                        BaseCommLocateInfo locateInfo = new BaseCommLocateInfo();
                        locateInfo.name = list.get(0).getTitle();
                        locateInfo.city = list.get(0).getCityName();
                        locateInfo.lat = list.get(0).getLatLonPoint().getLatitude() + "";
                        locateInfo.lon = list.get(0).getLatLonPoint().getLongitude() + "";
                        BaseSpUtils.getInstance().setCurrentCommuity(getActivity(), locateInfo);

                        neighborNearAddressTv.setText(list.get(0).getTitle());

                        hasCircle = BaseSpUtils.getInstance().getCircleStatus(getActivity());
                        if (hasCircle == 1) {
                            mPresenter.initUserNeighbor();
                        } else {
                            String com_lat = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lat;
                            String com_lon = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lon;
                            mPresenter.initNearNeighbor(com_lat, com_lon, page, size);
                        }

                    }
                } else {
                    mBaseLoadService.showCallback(LocationCallback.class);
                }
            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {

            }
        });

        LatLonPoint point = new LatLonPoint(lat, lon);
        poiSearch.setBound(new PoiSearch.SearchBound(point, 2000, true));
        poiSearch.searchPOIAsyn();

    }

    private void initRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        neighborNearRefresh.setOnRefreshListener(this);//刷新监听
        neighborNearRefresh.setEnableLoadMore(false);
        neighborNearRv.setHasFixedSize(true);
        neighborNearRv.setFocusable(false);
        neighborNearRv.setLayoutManager(layoutManager);

        adapter_circle = new NearCircleAdapter(R.layout.module_shoppingguide_item_circle_nearby, circle_list);
        adapter_circle.openLoadAnimation(BaseQuickAdapter.ALPHAIN);//加载动画
        adapter_circle.setOnLoadMoreListener(this, neighborNearRv);
        neighborNearRv.setAdapter(adapter_circle);

        adapter_circle.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(getActivity(), NeighborMessageActivity.class);
            intent.putExtra("circle_id", adapter_circle.getData().get(position).getId());
            startActivity(intent);

        });

        adapter_circle.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.tv_add_nearby_circle) {
                hasCircle = BaseSpUtils.getInstance().getCircleStatus(getActivity());
                if (hasCircle == 1) {
                    //已加入圈子
                    showNormal("你已经加入了一个圈子，目前仅允许加入一个圈子。需要加入新圈子，请先退出");
                } else if (hasCircle == 0) {
                    //未加入圈子
                    showLoading();
                    mPresenter.addNeighbor(adapter_circle.getData().get(position).getId());
                }
            }
        });
    }

    @Override
    public void isAddCircle(CircleMessageBean entity) {
        circle_id = entity.getId();
        entity_message = entity;
        String com_lat = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lat;
        String com_lon = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lon;
        mPresenter.initNearNeighbor(com_lat, com_lon, page, size);


    }

    @Override
    public void noAddCircle() {

    }

    @Override
    public void setNeighborNearData(NearCircleListBean entity) {
        mBaseLoadService.showSuccess();
        hasCircle = BaseSpUtils.getInstance().getCircleStatus(getActivity());

        if (hasCircle == 1) {
            neighborNearInfoLl.setVisibility(View.VISIBLE);

            //社区名
            neighborNearMessageName.setText(entity_message.getCircleName());
            //用户数量
            neighborNearMessageNum.setText(entity_message.getUserNum() + "位用户");

            if (null != entity_message.getHeadImages() && entity_message.getHeadImages().size() > 0) {
                if (entity_message.getHeadImages().size() == 1) {
                    if (!RxDataTool.isNullString(entity_message.getHeadImages().get(0))) {
                        neighborNearHeadIv1.setVisibility(View.VISIBLE);
                        GlideApp.with(getActivity())
                                .load(entity_message.getHeadImages().get(0))
                                .placeholder(R.mipmap.user_new_icon)
                                .error(R.mipmap.user_new_icon)
                                .into(neighborNearHeadIv1);
                    } else {
                        neighborNearHeadIv1.setVisibility(View.INVISIBLE);
                    }
                } else if (entity_message.getHeadImages().size() == 2) {
                    if (!RxDataTool.isNullString(entity_message.getHeadImages().get(0))) {
                        neighborNearHeadIv1.setVisibility(View.VISIBLE);
                        GlideApp.with(getActivity())
                                .load(entity_message.getHeadImages().get(0))
                                .placeholder(R.mipmap.user_new_icon)
                                .error(R.mipmap.user_new_icon)
                                .into(neighborNearHeadIv1);
                    } else {
                        neighborNearHeadIv1.setVisibility(View.INVISIBLE);
                    }

                    if (!RxDataTool.isNullString(entity_message.getHeadImages().get(1))) {
                        neighborNearHeadIv2.setVisibility(View.VISIBLE);
                        GlideApp.with(getActivity())
                                .load(entity_message.getHeadImages().get(1))
                                .placeholder(R.mipmap.user_new_icon)
                                .error(R.mipmap.user_new_icon)
                                .into(neighborNearHeadIv2);
                    } else {
                        neighborNearHeadIv2.setVisibility(View.INVISIBLE);
                    }
                } else if (entity_message.getHeadImages().size() >= 3) {
                    if (!RxDataTool.isNullString(entity_message.getHeadImages().get(0))) {
                        neighborNearHeadIv1.setVisibility(View.VISIBLE);
                        GlideApp.with(getActivity())
                                .load(entity_message.getHeadImages().get(0))
                                .placeholder(R.mipmap.user_new_icon)
                                .error(R.mipmap.user_new_icon)
                                .into(neighborNearHeadIv1);
                    } else {
                        neighborNearHeadIv1.setVisibility(View.INVISIBLE);
                    }

                    if (!RxDataTool.isNullString(entity_message.getHeadImages().get(1))) {
                        neighborNearHeadIv2.setVisibility(View.VISIBLE);
                        GlideApp.with(getActivity())
                                .load(entity_message.getHeadImages().get(1))
                                .placeholder(R.mipmap.user_new_icon)
                                .error(R.mipmap.user_new_icon)
                                .into(neighborNearHeadIv2);
                    } else {
                        neighborNearHeadIv2.setVisibility(View.INVISIBLE);
                    }

                    if (!RxDataTool.isNullString(entity_message.getHeadImages().get(2))) {
                        neighborNearHeadIv3.setVisibility(View.VISIBLE);
                        GlideApp.with(getActivity())
                                .load(entity_message.getHeadImages().get(2))
                                .placeholder(R.mipmap.user_new_icon)
                                .error(R.mipmap.user_new_icon)
                                .into(neighborNearHeadIv3);
                    } else {
                        neighborNearHeadIv3.setVisibility(View.INVISIBLE);
                    }
                }


            }

        } else {
            neighborNearInfoLl.setVisibility(View.GONE);
        }

        initNearList(entity);

    }

    @Override
    public void addNeighborSuccess(String circleId) {
        dismissLoading();
        showNormal("加入圈子成功");

        BaseSpUtils.getInstance().setCircleStatus(getActivity(), 1);

        if (null != adapter_circle) {
            adapter_circle.replaceData(new ArrayList<>());
        }

        EventBus.getDefault().post(new AppEvent(EventConfig.DELAYED_REFRESH_MINE_CIRCLE, circleId));
        hasCircle = BaseSpUtils.getInstance().getCircleStatus(getActivity());
        page = 0;
        mBaseLoadService.showCallback(LoadingCallback.class);

        //需要先将所有图片隐藏，在走接口，防止图片数量错乱
        inVisibleImgs();
        if (hasCircle == 1) {
            mPresenter.initUserNeighbor();
        } else {
            String com_lat = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lat;
            String com_lon = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lon;
            mPresenter.initNearNeighbor(com_lat, com_lon, page, size);
        }

    }

    @Override
    public void addNeighborFail(String s) {
        dismissLoading();
        showNormal("加入圈子失败");

    }

    private void initNearList(NearCircleListBean entity) {
        freshEnd();
        //总页数
        totalPage = entity.getPage().getTotalPages();

        if (totalPage <= 0) {
            //先设置空布局
            if (page == 0) {
                adapter_circle.replaceData(new ArrayList<>());
                adapter_circle.setEmptyView(noDataView);
                adapter_circle.notifyDataSetChanged();
            } else {
                adapter_circle.setEmptyView(noDataView);
                adapter_circle.notifyDataSetChanged();
            }
        } else {
            circle_list = entity.get_embedded().getContent();
            if (page == 0) {
                adapter_circle.setNewData(circle_list);
                //如果数据少 不显示已加载全部
                adapter_circle.disableLoadMoreIfNotFullPage();
            } else {
                adapter_circle.addData(circle_list);

            }
        }

        adapter_circle.loadMoreComplete();

    }

    @Override
    public void showError(String s) {
        freshEnd();
        mBaseLoadService.showCallback(ErrorCallback.class);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_LOC_SELECT && resultCode == RESULT_OK) {
            //选择地址返回
            mBaseLoadService.showCallback(LoadingCallback.class);
            neighborNearAddressTv.setText(BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).name);
            if (null != adapter_circle) {
                adapter_circle.replaceData(new ArrayList<>());
                adapter_circle.setEmptyView(loadingView);
            }

            page = 0;
            hasCircle = BaseSpUtils.getInstance().getCircleStatus(getActivity());

            //需要先将所有图片隐藏，在走接口，防止图片数量错乱
            inVisibleImgs();
            if (hasCircle == 1) {
                mPresenter.initUserNeighbor();
            } else {
                String com_lat = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lat;
                String com_lon = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lon;
                mPresenter.initNearNeighbor(com_lat, com_lon, page, size);
            }
        } else if (requestCode == CODE_COMMUNITY && resultCode == RESULT_OK) {
            //地图定位页面返回
            mBaseLoadService.showCallback(LoadingCallback.class);
            neighborNearAddressTv.setText(BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).name);
            if (null != adapter_circle) {
                adapter_circle.replaceData(new ArrayList<>());
                adapter_circle.setEmptyView(loadingView);
            }

            page = 0;
            hasCircle = BaseSpUtils.getInstance().getCircleStatus(getActivity());

            //需要先将所有图片隐藏，在走接口，防止图片数量错乱
            inVisibleImgs();
            if (hasCircle == 1) {
                mPresenter.initUserNeighbor();
            } else {
                String com_lat = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lat;
                String com_lon = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lon;
                mPresenter.initNearNeighbor(com_lat, com_lon, page, size);
            }
        }
    }

    private void inVisibleImgs() {
        neighborNearHeadIv1.setVisibility(View.INVISIBLE);
        neighborNearHeadIv2.setVisibility(View.INVISIBLE);
        neighborNearHeadIv3.setVisibility(View.INVISIBLE);

    }

    private void freshEnd() {
        if (null != neighborNearRefresh) {
            neighborNearRefresh.finishRefresh(200);
        }

    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        if (null != adapter_circle) {
            adapter_circle.setEnableLoadMore(false);
            adapter_circle.replaceData(new ArrayList<>());
            adapter_circle.setEmptyView(loadingView);
        }
        page = 0;
        String com_lat = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lat;
        String com_lon = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lon;
        mPresenter.initNearNeighbor(com_lat, com_lon, page, size);
        adapter_circle.setEnableLoadMore(true);

    }

    @Override
    public void onLoadMoreRequested() {
        neighborNearRefresh.setEnableRefresh(false);
        if (totalPage > 0) {
            if (page < totalPage - 1) {
                page++;
                String com_lat = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lat;
                String com_lon = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lon;
                mPresenter.initNearNeighbor(com_lat, com_lon, page, size);
                neighborNearRefresh.setEnableRefresh(true);
            } else {
                adapter_circle.loadMoreEnd();
                neighborNearRefresh.setEnableRefresh(true);
            }
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        EventBus.getDefault().register(this);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
        if (null != lm) {
            lm.stopLocation();
        }
    }

    @Override
    protected void clickError() {

    }

    @OnClick(R2.id.neighbor_near_info_ll)
    public void infoClick(View view) {
        if (!RxDataTool.isNullString(circle_id) ) {
            Intent intent = new Intent(getActivity(), NeighborMessageActivity.class);
            intent.putExtra("circle_id", circle_id);
            startActivity(intent);
        }


    }

    @OnClick(R2.id.neighbor_near_address_ll)
    public void addressClick(View view) {
        RouterCommonUtils.startNoParameterActivity(getActivity(), RouterIntentConstant.MODULE_SHOPPING_SELECT_ADDRESS_LIST, CODE_LOC_SELECT);

    }


}
